<template>
  <div class="app-container">

    <div class="filter-container">

      <el-input v-model="listQuery.filter['user_appointment.username']" placeholder="请输入用户名" style="width: 200px;"
                col="6"></el-input>

      <el-input v-model="listQuery.filter['user_appointment.phone']" placeholder="请输入手机号码" style="width: 200px;"
                col="6"></el-input>

      <el-input v-model="listQuery.filter['house.house_no']" placeholder="请输入房屋编号" style="width: 200px;"
                col="6"></el-input>

      <el-select v-model="listQuery.filter['user_appointment.status']" clearable placeholder="请选择状态">
        <el-option
          v-for="item in formSelections.statusList"
          :key="item.id"
          :label="item.title"
          :value="item.id">
        </el-option>
      </el-select>

      <el-button type="primary" @click="searchData">查询</el-button>
    </div>

    <el-table :data="list" border style="width: 100%" v-loading="listLoading" fit highlight-current-row>
      <el-table-column fixed prop="id" label="id" width="100"></el-table-column>
      <el-table-column prop="house.house_no" label=" 房屋编号" min-width="120"></el-table-column>
      <el-table-column prop="username" label=" 用户名" min-width="120"></el-table-column>
      <el-table-column prop="phone" label=" 手机号码" min-width="120"></el-table-column>
      <el-table-column prop="status" label=" 状态" min-width="120">
        <template slot-scope="scope">
          {{ statusFormat(scope.row.status)}}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="destroy(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page="page" :limit="listQuery.limit" :pageSizes="pageSizes"
                @pagination="pageChange"></pagination>

    <el-dialog :title="dialogTitle" :visible.sync="formDialogIsVisible">

      <el-form :model="formData" label-width="80px">

        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="first">

            <el-form-item label="用户头像">
              <el-image
                v-if="formData.user"
                style="width: 100px; height: 100px"
                :src="formData.user.wx_avatar"
                fit="contain"></el-image>
            </el-form-item>

            <el-form-item label="用户名">
              <el-input v-model="formData.username" :disabled="formData.is_complete === 2" autocomplete="off" placeholder="请输入用户名"></el-input>
            </el-form-item>

            <el-form-item label="手机号码">
              <el-input v-model="formData.phone" :disabled="formData.is_complete === 2" autocomplete="off" placeholder="请输入手机号码"></el-input>
            </el-form-item>

            <el-form-item label="预约时间">
              <el-date-picker
                :disabled="formData.is_complete === 2"
                v-model="formData.time"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="备注">
              <el-input v-model="formData.remark" :disabled="formData.is_complete === 2" type="textarea" autocomplete="off" rows="10"
                        placeholder="请输入备注信息"></el-input>
            </el-form-item>

            <el-form-item label="状态">
              <el-select v-model="formData.status" :disabled="formData.is_complete === 2" placeholder="请选择状态">
                <el-option
                  v-for="item in formSelections.statusList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="销售" v-if="formData.status === 2 && formData.is_complete === 1">
              <el-autocomplete
                popper-class="my-autocomplete"
                v-model="formData.sellerSearchName"
                :fetch-suggestions="querySearch"
                placeholder="请输入名称"
                @select="selectSeller" clearable>
                <template slot-scope="{ item }">
                  <div class="name">{{ item.nickname }}</div>
                  <span class="addr">{{ item.phone }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="房屋信息" name="second">

            <el-row>
              <el-col :span="24">
                <el-form-item label="图片">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="formData.house.photo"
                    :preview-src-list="getPhotos(formData.house.photoList)">
                  </el-image>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="标题">
                  <el-input v-model="formData.house.title" :disabled="true" autocomplete="off"
                            placeholder="请输入标题"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房屋编号">
                  <el-input v-model="formData.house.house_no" :disabled="true" autocomplete="off"
                            placeholder="请输入房屋编号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-form-item label="位置">
                <el-col :span="8">
                  <el-select v-model="formData.house.region_id" placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.region"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>

                <el-col :span="16">
                  <el-input v-model="formData.house.address_text" style="width: 100%;" :disabled="true"
                            autocomplete="off" placeholder="详细地址"></el-input>
                </el-col>
              </el-form-item>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="价格">
                  <el-input-number :precision="2" :step="0.01" :min="0" v-model="formData.house.amount"
                                   autocomplete="off" :disabled="true"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="折扣价">
                  <el-input-number :precision="2" :step="0.01" :min="0" v-model="formData.house.discount_rate"
                                   autocomplete="off" :disabled="true"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="面积">
                  <el-input-number :precision="2" :step="0.01" :min="0" v-model="formData.house.area"
                                   autocomplete="off" :disabled="true"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="楼层">
                  <el-input :min="1" v-model="formData.house.floor" :disabled="true" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="朝向">
                  <el-select v-model="formData.house.orientation_id" placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.orientation"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="户型">
                  <el-select v-model="formData.house.layout_id" placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.layout"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="轻轨线">
                  <el-select v-model="formData.house.subway_line_id" multiple placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.subwayLine"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="配套设置">
                  <el-select v-model="formData.house.infrastructure_id" multiple placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.infrastructure"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="标签">
                  <el-select v-model="formData.house.tags" multiple placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.tag"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="租赁方式">
                  <el-select v-model="formData.house.type_id" multiple placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in formSelections.houseType"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-form-item label="状态">
                <el-select v-model="formData.house.status" placeholder="请选择" :disabled="true">
                  <el-option
                    v-for="item in formSelections.houseStatusList"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>

            <el-form-item label="描述">
              <el-input type="textarea" v-model="formData.house.desc" autocomplete="off" :disabled="true"
                        placeholder="请输入描述内容"></el-input>
            </el-form-item>

          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formDialogIsVisible = false">取 消</el-button>
        <el-button type="primary" @click="save" v-if="formData.is_complete === 1">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {getStatusList as getHouseStatusList} from '@/api/house'
  import {fetchList as getUserList} from '@/api/user'
  import {fetchList, getStatusList, update, destroy, getHousePassword} from '@/api/userAppointment'
  import * as houseType from '@/api/houseType'
  import * as layout from '@/api/layout'
  import * as infrastructure from '@/api/infrastructure'
  import * as orientation from '@/api/orientation'
  import * as region from '@/api/region'
  import * as tag from '@/api/tag'
  import * as subwayLine from '@/api/subwayLine'
  import Pagination from '@/components/Pagination'

  export default {
    name: 'user_appointment',
    components: {Pagination},
    data() {
      return {
        //  tab切换标志
        activeTab: "first",
        list: null,
        total: 0,
        page: 1,
        pageSizes: [
          10, 20, 30
        ],
        listLoading: true,
        listQuery: {
          offset: 0,
          limit: 10,
          filter: {
            "user_appointment.username": null,
            "user_appointment.phone": null,
            "user_appointment.status": undefined,
            "house.house_no": null,
          },
          options: {
            "user_appointment.username": "like",
            "user_appointment.phone": "like",
            "house.house_no": "like",
          }
        },
        formDialogIsVisible: false,
        formMode: "add",
        formData: {
          sellerSearchName: undefined,
          id: undefined,
          username: undefined,
          phone: undefined,
          time: undefined,
          house_id: undefined,
          is_complete: undefined,
          status: undefined,
          remark: undefined,
          user: undefined,
          user_id: undefined,
          seller: undefined,
          house: {
            id: undefined,
            title: undefined,
            house_no: undefined,
            photoList: [],
            type_id: [],
            layout_id: undefined,
            amount: 0.00,
            discount_rate: 1,
            region_id: 1,
            area: 0,
            status: undefined,
            floor: 1,
            address_text: undefined,
            tags: [],
            infrastructure_id: [],
            longitude: undefined,
            latitude: undefined,
            orientation_id: undefined,
            subway_line_id: [],
            desc: undefined
          }
        },
        formSelections: {
          tag: [],
          houseType: [],
          layout: [],
          infrastructure: [],
          orientation: [],
          region: [],
          subwayLine: [],
          houseStatusList: [],
          statusList: [],
          sellerList: [],
        },
      }
    },
    computed: {
      dialogTitle() {
        return this.formMode === "add" ? "新增" : "编辑"
      },
    },
    created() {
      this.getList();
      this._initData();
    },
    methods: {
      selectSeller(user) {
        this.formData.sellerSearchName = user.nickname;
        this.formData.seller_id = user.id;
        this.formData.seller = Object.assign({}, user);
      },
      querySearch(queryString, cb) {
        let list = this.formSelections.sellerList;
        var results = queryString ? list.filter(this.createFilter(queryString)) : list;
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.nickname.toLowerCase().indexOf(queryString.toLowerCase()) === 0 || restaurant.phone.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      statusFormat(status) {
        let text = "未知";
        this.formSelections.statusList.forEach(item => {
          if (parseInt(item.id) === status) text = item.title;
        });
        return text;
      },
      getPhotos(photos) {
        return photos.map(item => {
          return item.url;
        });
      },
      async _initData() {
        let searchQuery = {
          infinite: true,
        };
        let houseTypeList = await houseType.fetchList(searchQuery);
        let layoutList = await layout.fetchList(searchQuery);
        let infrastructureList = await infrastructure.fetchList(searchQuery);
        let orientationList = await orientation.fetchList(searchQuery);
        let regionList = await region.fetchList(searchQuery);
        let tagList = await tag.fetchList(searchQuery);
        let subwayLineList = await subwayLine.fetchList(searchQuery);
        let houseStatusList = await getHouseStatusList();
        let statusList = await getStatusList();
        let sellerList = await getUserList({
          filter: {
            type: 2
          }
        });

        this.formSelections.houseStatusList = houseStatusList.data;
        this.formSelections.statusList = statusList.data;
        this.formSelections.layout = layoutList.data.list;
        this.formSelections.houseType = houseTypeList.data.list;
        this.formSelections.infrastructure = infrastructureList.data.list;
        this.formSelections.orientation = orientationList.data.list;
        this.formSelections.region = regionList.data.list;
        this.formSelections.tag = tagList.data.list;
        this.formSelections.subwayLine = subwayLineList.data.list;
        this.formSelections.sellerList = sellerList.data.list;
      },
      pageChange(data) {
        this.page = data.page;
        this.listQuery.limit = data.limit;
        this.listQuery.offset = (this.page - 1) * this.listQuery.limit;
        this.refresh(false);
      },
      openDialog(row) {
        this.activeTab = "first";
        this.formDialogIsVisible = true;
        this.formMode = "edit";
        let house = row.house;
        this.formData = {
          id: row.id,
          username: row.username,
          sellerSearchName: undefined,
          phone: row.phone,
          amount: row.amount,
          house_id: row.house_id,
          time: row.time,
          is_complete: row.is_complete,
          status: row.status,
          remark: row.remark,
          user: Object.assign({}, row.user),
          user_id: row.user_id,
          house: {
            title: house.title,
            house_no: house.house_no,
            photoList: Object.assign([], house.photoList),
            photo: house.photoList[0].url,
            type_id: house.type_id,
            layout_id: house.layout_id,
            amount: house.amount,
            discount_rate: house.discount_rate,
            region_id: house.region_id,
            area: house.area,
            status: house.status,
            floor: house.floor,
            address_text: house.address_text,
            tags: house.tags,
            infrastructure_id: house.infrastructure_id,
            longitude: house.longitude,
            latitude: house.latitude,
            orientation_id: house.orientation_id,
            subway_line_id: house.subway_line_id,
            desc: house.desc
          }
        };
      },
      save() {
        let promise;
        this.listLoading = true;
        let formData = this.formData;
        promise = update(this.formData);
        promise.then(() => {
          this.refresh();
        }).catch(() => {
          this.listLoading = false;
        });
      },
      destroy(id) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.listLoading = true;
          await destroy({id});
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((error) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        }).finally(() => {
          this.refresh();
        });
      },
      searchData() {
        this.refresh(true);
      },
      refresh(isAll = false) {
        this.formDialogIsVisible = false;
        this.listLoading = false;
        if (isAll) {
          this.page = 1;
        }
        this.getList();
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          let {data} = response;
          this.list = data.list
          this.total = response.data.count
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        });
      },
    },
    watch: {
      page: function (newVluae, oldVluae) {
        this.listQuery.offset = (newVluae - 1) * this.listQuery.limit;
      },
    },
  }
</script>
<style lang="scss">
  .photos-uploader {
    .el-upload-list__item {
      width: 140px;
      height: 105px;
    }

    .el-upload.el-upload--picture-card {
      width: 140px;
      height: 105px;
      line-height: 105px;
    }
  }


  .map_container {
    width: 100%;
    position: relative;
    height: 480px;
    display: table;
  }
</style>
